from django.shortcuts import render, get_object_or_404, redirect
from .models import *
from .forms import CommentForm
# Create your views here.

def article_list(request):
    return render(request, 'blog/article_list.html')

def article_detail(request, pk):
    article = get_object_or_404(Article, pk=pk)
    article.increase_views(request)
    comments = article.comments.filter(parent__isnull=True)
    if request.method == 'POST':
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            comment = comment_form.save(commit=False)
            comment.article = article
            comment.author = request.user
            reply_to_id = request.POST.get('reply_to_id')
            if reply_to_id:
                comment.reply_to = Comment.objects.get(id=reply_to_id)
                comment.parent = comment.reply_to.parent if comment.reply_to.parent else comment.reply_to
            comment.save()
            return redirect(f"{article.get_absolute_url()}#comment-{comment.id}")
    else:
        comment_form = CommentForm()
    return render(request, 'blog/article_detail.html', {
        'article': article,
        'comment_form': comment_form,
        'comments': comments,
    })

def category(request, pk):
    category = get_object_or_404(Category, pk=pk)
    return render(request, 'blog/category.html', {'category': category})

def tag(request, pk):
    tag = get_object_or_404(Tag, pk=pk)
    return render(request, 'blog/tag.html', {'tag': tag})

def archive(request):
    articles = Article.objects.all().order_by('create_at')
    return render(request, 'blog/archive.html', {'articles': articles})
